home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3753 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  76 lines

  1. Path: news.Stanford.EDU!not-for-mail
  2. From: brien@leland.Stanford.EDU (brien oberstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Copy constructing an already default constructed object
  5. Date: 25 Jan 1996 14:28:27 -0800
  6. Organization: Stanford University
  7. Message-ID: <4e906b$stk@elaine32.Stanford.EDU>
  8. NNTP-Posting-Host: elaine32.stanford.edu
  9. X-Newsreader: NN version 6.5.0 (NOV)
  10.  
  11. I'd like to get some opinions on the best/cleanest way
  12. to accomplish the following:
  13.  
  14. I've got an object which has already been constructed
  15. via its default constructor which just sets all pointers
  16. to NULL.  Whats the best way to deep-copy into it?
  17.  
  18.  
  19. class A {
  20. public:
  21.   A();             // default ctor
  22.   A(const A&)      // copy ctor
  23.   A(const char *)  // convert ctor 
  24. }; 
  25.  
  26. somefunc()
  27. {
  28.   ...
  29.   A a0;
  30.   ...
  31.   A a1("blah");
  32.  
  33.   //
  34.   // How do you deep copy a1 into a0 ???
  35.   //
  36.   a0 = a1;         // no good. shallow copy
  37.   a0 = A(a1);         // no good. dtor called for temp A object
  38.   a0 = *new A(a1);   // no good. creates memory for a A object
  39.  
  40.   //
  41.   // the follow works but is tedious
  42.   //
  43.   A empty;         // create an empty object
  44.   A tmp(a1);         // deep-copy a1 to temp
  45.   a0 = tmp;         // shallow-copy temp to a0
  46.   tmp = empty;         // clear out temp so internals are not destructed
  47.  
  48.   //
  49.   // so overload = to make deep copies
  50.   //
  51.   a0 = a1;
  52.  
  53. }
  54.  
  55. //
  56. // deep-copy =
  57. //
  58. A& A::operator =(const A& other)
  59. {
  60.   A empty;
  61.   A tmp(other);
  62.   memcpy(this, &tmp, sizeof(A));
  63.   memcpy(&tmp, &empty, sizeof(A));
  64.   return *this;
  65. }
  66.  
  67.  
  68. I'd like to know what people think of the solution I've reached.
  69. I figure that this type of shit is common enough so there should 
  70. be some widely accepted solution to this problem.  Or maybe its
  71. not, but believe me that the situation does occur.
  72.  
  73. Thanks,
  74.   brien
  75.  
  76.